package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Adapter.DTDetailCommAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Adapter.PJGridAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Adapter.ZanGVAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CommentListView;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.DDPopupWindow;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.NoScrollPFGridView;
import com.cloudxingkong.dianyinke.NewTeacher.bean.DongTaiDetail;
import com.cloudxingkong.dianyinke.NewTeacher.bean.Likes;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Class.MyGridView;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class DontaiDetailActivity extends AppCompatActivity implements DDPopupWindow.setOnClickPopupWindowListener, AdapterView.OnItemClickListener {

    private CircleImageView ccTouxiang;  //动态详情用户头像
    private TextView tvName;    //动态详情用户名称
    private TextView tvContent;   //动态详情内容
    private CommentListView lvPingLun;
    private ImageButton ivMore;  //更多按钮
    private MyGridView layoutZan;  //赞gridview
    private String dtID;     //动态ID
    private SharedPreferences sharedPreferences;
    private String sessionID;
    private RelativeLayout pbFrame;   //带有progressbar的layout
    private NoScrollPFGridView ddGridView;   //动态图片gridview
    private TextView tvDate;    //时间
    private String avatarPath;   //从sp中获得的用户头像
    private DDPopupWindow pw;
    private LinearLayout ddCommentLayout;   //发送评论的布局
    private EditText etComment;
    private Button btnComment;
    private List<DongTaiDetail.ObjBean.DynamicdetlBean> dynamicData;  //评论集合
    private List<Likes> zanList;   //赞集合
    private DTDetailCommAdapter commAdapter;  //评论适配器
    private ZanGVAdapter zanGVAdapter;    //赞适配器
    private LinearLayout zanLayout;
    private LinearLayout plLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dontai_detail);
        init();
        loadData();
    }

    //请求整个详情数据
    private void loadData() {
        pbFrame.setVisibility(View.VISIBLE);
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.NAMIC_QRY);
        params.addHeader("cookie",sessionID);
        params.addBodyParameter("dynamicid", dtID);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pbFrame.setVisibility(View.GONE);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:    //页面数据加载
                    String result= (String) msg.obj;
                    Log.e("test", "动态详情 " + result);
                    pbFrame.setVisibility(View.GONE);
                    DongTaiDetail objBean = (new Gson()).fromJson(result, DongTaiDetail.class);
                    if (objBean.isSuccess()){
                        //得到评论数据  getDynamicdetl
                        List<DongTaiDetail.ObjBean.DynamicdetlBean> dynamicdetl = objBean.getObj().getDynamicdetl();
                        dynamicData.clear();
                        zanList.clear();
                        /**
                         * 遍历集合
                         * 将赞数据与评论数据抽取
                         * 分别填充
                         */
                        for (DongTaiDetail.ObjBean.DynamicdetlBean bean : dynamicdetl) {
                            //评论
                            if (bean.getType().equals(Constans.TYPE_COMMENT)) {
                                dynamicData.add(bean);
                                if (dynamicData.size() > 0) {
                                    plLayout.setVisibility(View.VISIBLE);
                                    commAdapter.notifyDataSetChanged();
                                }
                            }
                            //赞
                            if (bean.getType().equals(Constans.TYPE_ZAN)) {
                                String zanAvatar = bean.getAvatar().toString();
                                int id = bean.getId();
                                String memname = bean.getMemname();
                                Likes likes = new Likes(zanAvatar, id, memname);
                                likes.setUserAvatar(zanAvatar);
                                likes.setUserId(id);
                                likes.setUserMemename(memname);
                                Log.e("test", "赞 " + id + " - " + memname + " - " + zanAvatar);
                                zanList.add(likes);
                                if (zanList.size() > 0) {
                                    zanLayout.setVisibility(View.VISIBLE);
                                    zanGVAdapter.notifyDataSetChanged();
                                }
                            }
                        }

                        /**
                         * 加载动态详情数据
                         */
                        //加载动态图片
                        String pics = objBean.getObj().getDynamicinfo().getPics();
                        if (!pics.equals("")&&pics != null) {
                            final String[] split = pics.split(",");
                            if (!pics.equals("")){
                                if (pics.indexOf(",")==-1) {
                                    split[0]=pics;
                                    ddGridView.setVisibility(View.VISIBLE);
                                    ddGridView.setAdapter(new PJGridAdapter(split, DontaiDetailActivity.this));
                                    ddGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            imageBrower(position,split);
                                        }
                                    });
                                }else{
                                    ddGridView.setVisibility(View.VISIBLE);
                                    ddGridView.setAdapter(new PJGridAdapter(split, DontaiDetailActivity.this));
                                    ddGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            imageBrower(position,split);
                                        }
                                    });
                                }
                            }else{
                                ddGridView.setVisibility(View.GONE);
                            }
                        }else{
                            ddGridView.setVisibility(View.GONE);
                        }
                        //填充动态时间
                        String ts = objBean.getObj().getDynamicinfo().getTs();
                        String dateSub = ts.substring(ts.indexOf("-") + 1, ts.indexOf(":") + 3);
                        tvDate.setText(dateSub);
                    }else {
                        Toast.makeText(DontaiDetailActivity.this, "获取详情失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:   //删除动态处理
                    String delResult= (String) msg.obj;
                    if (delResult.contains("true")) {
                        pbFrame.setVisibility(View.GONE);
                        Toast.makeText(DontaiDetailActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                        setResult(318);
                        finish();
                    }else{
                        pbFrame.setVisibility(View.GONE);
                        Toast.makeText(DontaiDetailActivity.this,"删除失败",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 3:  //评论结果处理
                    boolean isComm=false;
                    String comResult = (String) msg.obj;
                    Log.e("test", "评论结果 " + comResult);
                    Object success = LoginJsonUtils.getJsonFromLogin(comResult).get("success");
                    isComm= (boolean) success;
                    if (isComm) {
                        plLayout.setVisibility(View.VISIBLE);
                        Toast.makeText(DontaiDetailActivity.this, "评论成功!", Toast.LENGTH_SHORT).show();
                        etComment.setText("");
                        pbFrame.setVisibility(View.GONE);
                        ddCommentLayout.setVisibility(View.GONE);
                        commAdapter.clear();
                        loadData();
                    }else{
                        Toast.makeText(DontaiDetailActivity.this, "评论失败,请重试!", Toast.LENGTH_SHORT).show();
                        pbFrame.setVisibility(View.GONE);
                    }
                    break;
                case 4:   //赞成功将progressbar隐藏 重新加载页面数据
                    pbFrame.setVisibility(View.GONE);
                    zanLayout.setVisibility(View.VISIBLE);
                    loadData();
                    break;
                case 5:  //赞失败
                    Toast.makeText(DontaiDetailActivity.this, "赞失败", Toast.LENGTH_SHORT).show();
                    pbFrame.setVisibility(View.GONE);
                    break;
            }
        }
    };


    private void imageBrower(int position, String[] pics) {
        try {
            Intent intent = new Intent(this, ImagePagerActivity.class);
            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, pics);
            this.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始化参数
     */
    private void init() {
        pbFrame = (RelativeLayout) findViewById(R.id.pb_layout_dongtai_detail);
        ddGridView = (NoScrollPFGridView) findViewById(R.id.dd_primary_gridview);
        tvDate = (TextView) findViewById(R.id.dd_primary_date);
        ccTouxiang = (CircleImageView) findViewById(R.id.dd_ci_touxiang);    //用户头像
        tvName = (TextView) findViewById(R.id.dd_primary_name);    //老师姓名
        tvContent = (TextView) findViewById(R.id.dd_primary_tv_content);  //动态详情文字
        ivMore = (ImageButton) findViewById(R.id.dd_primary_btn_more);   //查看更多
        layoutZan = (MyGridView) findViewById(R.id.dd_gridview_zan);    //赞的人

        //评论点赞
        zanLayout = (LinearLayout) findViewById(R.id.dd_layout_zan);
        plLayout = (LinearLayout) findViewById(R.id.dd_layout_pinglun);
        ddCommentLayout = (LinearLayout) findViewById(R.id.dd_comment_layout);
        etComment = (EditText) findViewById(R.id.dd_et_comment);
        btnComment = (Button) findViewById(R.id.dd_btn_sendcomment);
        lvPingLun = (CommentListView) findViewById(R.id.dd_listview_comm);    //评论列表
        dynamicData=new ArrayList<>();   //评论数据
        zanList=new ArrayList<>();  //赞数据
        //评论列表以及适配器
        commAdapter = new DTDetailCommAdapter(dynamicData,this);
        lvPingLun.setAdapter(commAdapter);
        //赞layout以及适配器
        zanGVAdapter = new ZanGVAdapter(zanList,this);
        layoutZan.setAdapter(zanGVAdapter);
        layoutZan.setOnItemClickListener(this);


        Intent intent = getIntent();
        dtID = intent.getStringExtra("dtID");
        Log.e("test","动态详情中的动态ID "+dtID);
        String text = intent.getStringExtra("text");
        String tMemname = intent.getStringExtra("tMemname");
        tvName.setText(tMemname);
        tvContent.setText(text);
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);

        avatarPath = sharedPreferences.getString("qryTavatar", "");
        ddGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        layoutZan.setSelector(new ColorDrawable(Color.TRANSPARENT));

        if (!avatarPath.equals("") && avatarPath != null) {
            ImageLoader.getInstance().displayImage(avatarPath,ccTouxiang);
        }


    }

    //返回
    public void back(View view) {
        finish();
    }

    //删除
    public void delete(View view) {
        new AlertDialog.Builder(this)
                .setMessage("删除此条评论吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        pbFrame.setVisibility(View.VISIBLE);
                        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.NAMIC_DEL);
                        params.addHeader("cookie",sessionID);
                        params.addBodyParameter("dynamicid", dtID);
                        x.http().post(params, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                Log.e("test", "删除动态结果 : " + result);
                                Message msg = handler.obtainMessage();
                                msg.what = 2;
                                msg.obj = result;
                                handler.sendMessage(msg);
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                pbFrame.setVisibility(View.GONE);
                            }

                            @Override
                            public void onCancelled(CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    }
                })
                .setNegativeButton("取消",null).create().show();
    }
    //更多  弹出popupWindow
    public void more(View view) {
        pw = new DDPopupWindow(this,this);
        pw.showPopupWindow(ivMore);
    }
    /**
     * PopupWindow回调
     * @param v  赞按钮
     */
    @Override
    public void onClickZan(View v) {

        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constans.ONLY_ONE_ZAN==-1) {  //TODO 只能赞一次
                    pbFrame.setVisibility(View.VISIBLE);
                    Toast.makeText(DontaiDetailActivity.this, "赞", Toast.LENGTH_SHORT).show();
                    pw.dismiss();
                    postZan();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void postZan() {

        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.COMMENT_OR_MSG);
        params.addHeader("cookie",sessionID);
        params.addBodyParameter("dynamicid", dtID);
        params.addBodyParameter("type", "like");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                boolean isPostZan = false;
                Log.e("test", "老师点赞结果 " + result);
                if (result != null && !result.equals("")) {
                    Object success = LoginJsonUtils.getJsonFromLogin(result).get("success");
                    isPostZan = (boolean) success;
                    if (isPostZan) {
                        handler.sendEmptyMessage(4);
                    } else {
                        handler.sendEmptyMessage(5);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pbFrame.setVisibility(View.GONE);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * PopupWindow回调
     * @param v  评论按钮
     */
    @Override
    public void onClickComment(View v) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(DontaiDetailActivity.this,"评论",Toast.LENGTH_SHORT).show();
                pw.dismiss();
                ddCommentLayout.setVisibility(View.VISIBLE);
                postComment();
            }
        });
    }

    /**
     * 发表评论
     */
    private void postComment() {
        btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etComment.getText().toString())) {
                    pbFrame.setVisibility(View.VISIBLE);
                    String comment = etComment.getText().toString();
                    RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.COMMENT_OR_MSG);
                    params.addHeader("cookie", sessionID);
                    params.addBodyParameter("dynamicid", dtID);
                    params.addBodyParameter("type", "msg");
                    params.addBodyParameter("msg", comment);
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {

                            Message msg = handler.obtainMessage();
                            msg.what = 3;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            pbFrame.setVisibility(View.GONE);
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });

                } else {
                    Toast.makeText(DontaiDetailActivity.this, "您还未输入评论", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String userMemename = zanList.get(position).getUserMemename();
        Toast.makeText(DontaiDetailActivity.this, userMemename, Toast.LENGTH_SHORT).show();
    }
}
